<template>
  <div class="employees">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索员工姓名或工号"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch">
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="departmentFilter" placeholder="选择部门" clearable @change="handleSearch">
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="statusFilter" placeholder="在职状态" clearable @change="handleSearch">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="离职" value="离职"></el-option>
          </el-select>
        </el-col>
        <el-col :span="10" style="text-align: right">
          <el-button type="primary" @click="handleAdd">新增员工</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 员工列表 -->
    <el-table
      v-loading="loading"
      :data="employees"
      border
      style="width: 100%">
      <el-table-column prop="employee_id" label="工号" width="100"></el-table-column>
      <el-table-column prop="name" label="姓名" width="100"></el-table-column>
      <el-table-column prop="gender" label="性别" width="80"></el-table-column>
      <el-table-column prop="department_name" label="部门" width="120"></el-table-column>
      <el-table-column prop="position" label="职位" width="120"></el-table-column>
      <el-table-column prop="phone" label="电话" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="hire_date" label="入职日期" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '在职' ? 'success' : 'info'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 员工表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm">
      <el-form
        ref="employeeForm"
        :model="employeeForm"
        :rules="rules"
        label-width="100px">
        <el-form-item label="工号" prop="employee_id">
          <el-input v-model="employeeForm.employee_id" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="employeeForm.gender" style="width: 100%">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth_date">
          <el-date-picker
            v-model="employeeForm.birth_date"
            type="date"
            placeholder="选择日期"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="employeeForm.id_card" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="employeeForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="employeeForm.email"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="employeeForm.address"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="department_id">
          <el-select v-model="employeeForm.department_id" style="width: 100%">
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="employeeForm.position"></el-input>
        </el-form-item>
        <el-form-item label="入职日期" prop="hire_date">
          <el-date-picker
            v-model="employeeForm.hire_date"
            type="date"
            placeholder="选择日期"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="employeeForm.status" style="width: 100%">
            <el-option label="在职" value="在职"></el-option>
            <el-option label="离职" value="离职"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Employees',
  data() {
    return {
      // 表格数据
      employees: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 搜索和筛选
      searchQuery: '',
      departmentFilter: '',
      statusFilter: '',
      departments: [],

      // 对话框
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      submitting: false,
      employeeForm: {
        employee_id: '',
        name: '',
        gender: '',
        birth_date: '',
        id_card: '',
        phone: '',
        email: '',
        address: '',
        department_id: '',
        position: '',
        hire_date: '',
        status: '在职'
      },
      rules: {
        employee_id: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        id_card: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        department_id: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        hire_date: [
          { required: true, message: '请选择入职日期', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchDepartments()
    this.fetchEmployees()
  },
  methods: {
    // 获取部门列表
    async fetchDepartments() {
      try {
        const response = await axios.get('/api/departments/')
        this.departments = response.data
      } catch (error) {
        this.$message.error('获取部门列表失败')
      }
    },

    // 获取员工列表
    async fetchEmployees() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          per_page: this.pageSize,
          search: this.searchQuery,
          department_id: this.departmentFilter,
          status: this.statusFilter
        }
        const response = await axios.get('/api/employees/', { params })
        this.employees = response.data.items
        this.total = response.data.total
      } catch (error) {
        this.$message.error('获取员工列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchEmployees()
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchEmployees()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchEmployees()
    },

    // 新增员工
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增员工'
      this.dialogVisible = true
    },

    // 编辑员工
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑员工'
      this.employeeForm = { ...row }
      this.dialogVisible = true
    },

    // 删除员工
    handleDelete(row) {
      this.$confirm('确认删除该员工吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await axios.delete(`/api/employees/${row.id}/`)
          this.$message.success('删除成功')
          this.fetchEmployees()
        } catch (error) {
          this.$message.error(error.response?.data?.error || '删除失败')
        }
      }).catch(() => {})
    },

    // 提交表单
    submitForm() {
      this.$refs.employeeForm.validate(async valid => {
        if (valid) {
          this.submitting = true
          try {
            if (this.isEdit) {
              await axios.put(`/api/employees/${this.employeeForm.id}/`, this.employeeForm)
              this.$message.success('更新成功')
            } else {
              await axios.post('/api/employees/', this.employeeForm)
              this.$message.success('创建成功')
            }
            this.dialogVisible = false
            this.fetchEmployees()
          } catch (error) {
            this.$message.error(error.response?.data?.error || '操作失败')
          } finally {
            this.submitting = false
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      this.$refs.employeeForm?.resetFields()
      this.employeeForm = {
        employee_id: '',
        name: '',
        gender: '',
        birth_date: '',
        id_card: '',
        phone: '',
        email: '',
        address: '',
        department_id: '',
        position: '',
        hire_date: '',
        status: '在职'
      }
    }
  }
}
</script>

<style scoped>
.employees {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 